from PIL import Image
import os
from tqdm import tqdm
def png_to_jpg(png_path, jpg_path):
    # 打开png文件
    with Image.open(png_path) as img:
        # 保存为JPG格式
        img.convert("RGB").save(jpg_path, "JPEG")
    print(f"成功将 {png_path} 转换为 {jpg_path}")

# 示例：批量转换文件夹中的所有png文件为JPG
def batch_convert(png_folder, jpg_folder,remove_png):
    # 如果输出文件夹不存在，创建它
    if not os.path.exists(jpg_folder):
        os.makedirs(jpg_folder)

    # 遍历文件夹中的所有png文件
    for filename in tqdm(os.listdir(png_folder)):
        if filename.lower().endswith(".png"):
            png_path = os.path.join(png_folder, filename)
            jpg_filename = filename.replace(".png", ".jpg")
            jpg_path = os.path.join(jpg_folder, jpg_filename)
            png_to_jpg(png_path, jpg_path)
            if remove_png:os.remove(png_path)

# 示例：批量转换指定文件夹中的png文件为JPG
png_folder = r"/data/shengjie/synthesis_zhenzhi/"  # 替换为你的png文件夹路径
jpg_folder = r"/data/shengjie/synthesis_zhenzhi/"  # 替换为保存JPG文件的文件夹路径
# 转换jpg后是否移除原有的png文件
remove_png = True

batch_convert(png_folder, jpg_folder,remove_png=remove_png)